package com.ervanalb.cellradio.shared.communicator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.ByteBuffer;

import com.ervanalb.cellradio.shared.communicator.packets.Packet;

/**
 * A PacketSink which dispenses with its packets through a DatagramSocket.
 * 
 * @author eric
 */
public class SocketSink implements PacketSink {
	DatagramSocket sock;
	int port;

	public SocketSink(int port) throws SocketException {
		sock = new DatagramSocket();
		this.port = port;
	}

	@Override
	public void send(Packet p) throws IOException {
		synchronized (sock) {
			ByteBuffer b = p.render();
			byte[] arr = new byte[b.remaining()];
			b.get(arr);
			DatagramPacket sendPacket = new DatagramPacket(arr, arr.length,
					p.addr, port);

			// System.out.println("Send: "+p);
			sock.send(sendPacket);
		}
	}
}
